package com.liao.note.util;

import okhttp3.*;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class PutAudioToAI {

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String[] args) {
//        putAudioToAI()
    }

    public static JSONObject putAudioToAI(String path) throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/json");
        // speech 可以通过 getFileContentAsBase64("C:\fakepath\ji6.m4a") 方法获取
        System.out.println("path----------" + path);
        FileInputStream fis = new FileInputStream(new File(path));
        String content = getFileContentAsBase64(path);
        String s = aa();
        RequestBody body = RequestBody.create(mediaType, "{\"format\":\"wav\",\"rate\":16000,\"channel\":1,\"cuid\":\"a\",\"token\":\"" + s + "\",\"speech\":\"" + content + "\",\"len\":" + fis.available() + "}");
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/server_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String string = response.body().string();
        System.out.println(string);
        return new JSONObject(string);
    }

    public static final String API_KEY = "I0myuOSpLLlL1KWEz90rdEuz";
    public static final String SECRET_KEY = "VOwTqTwulFzbIf68poKThxoKxl9Vp6E2";

    /**
     * 获取文件base64编码
     *
     * @param path 文件路径
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    private static String getFileContentAsBase64(String path) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        return Base64.getEncoder().encodeToString(b);
    }

    private static String aa() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String access_token = new JSONObject(response.body().string()).getString("access_token");
        return access_token;
    }


}
